package com.myblog.controller;


import cn.hutool.core.util.StrUtil;
import com.myblog.constant.EmailConstant;
import com.myblog.constant.Roles;
import com.myblog.constant.UserConstant;
import com.myblog.entity.Result;
import com.myblog.entity.Users;
import com.myblog.entity.dto.LoginDTO;
import com.myblog.entity.dto.UserDTO;
import com.myblog.entity.vo.UserVO;
import com.myblog.service.IUsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沙琪马
 * @since 2024-06-21
 */
@RestController
@RequestMapping("/users")
@Tag(name = "用户管理", description = "用户管理相关接口")
@Slf4j
public class UsersController {

    @Resource
    private IUsersService userService;

    /**
     * 登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result<UserVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户{}登录", loginDTO.getUsername());
        // 1.根据 loginDTO 决定使用邮箱登录还是用户名登录
        UserVO login = null;
        if(StrUtil.isNotBlank(loginDTO.getUsername())){
            login = userService.loginByUsername(loginDTO);
        }else if(StrUtil.isNotBlank(loginDTO.getEmail())){
            login = userService.loginByEmail(loginDTO);
        }else{
            throw new RuntimeException(UserConstant.UNKNOWN_ERROR);
        }
        ;
        return Result.success(login);
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "注册用户")
    public Result<Boolean> registerUsers(@RequestBody UserDTO user){
        // 1. 设置默认角色
        user.setRole(Roles.USER);
        // 2. 注册用户
        userService.registerUsers(user);
        return Result.success();
    }

    @PostMapping("/sendCode")
    @Operation(summary = "发送验证码")
    public Result<String> sendVerificationCode(@RequestParam String email) {
        log.info("发送验证码给{}", email);
        userService.sendVerificationCode(email);
        return Result.success(EmailConstant.EMAIL_SEND_SUCCESS);
    }

    @GetMapping
    @Operation(summary = "测试接口")
    public Users test() {
        Users users = new Users();
        users.setUsername("沙琪马");
        users.setPassword("123456");
        users.setEmail("2375211058@qq.com");
        return users;
    }

}
